#import "USFeedbackTool.h"

@implementation USFeedbackTool

static BOOL _us_feedback_enabled = YES;
static NSTimeInterval _lastFeedbackTime = 0;
static NSTimeInterval _feedbackInterval = 0.08;

//+ (void)setEnabled:(BOOL)enabled {
//    _us_feedback_enabled = enabled;
//}

+ (BOOL)isEnabled {
    return [[NSUserDefaults standardUserDefaults]boolForKey:USPrefKey_EnableFeedback];
}

+ (BOOL)canTriggerFeedback {
    NSTimeInterval now = [NSDate date].timeIntervalSince1970;
    if (now - _lastFeedbackTime < _feedbackInterval) {
        return NO;
    }
    _lastFeedbackTime = now;
    return YES;
}

+ (void)impactWithStyle:(UIImpactFeedbackStyle)style {
    if (![self isEnabled] || ![self canTriggerFeedback]) return;
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:style];
        [generator impactOccurred];
    }
}

+ (void)impactLight  { [self impactWithStyle:UIImpactFeedbackStyleLight]; }
+ (void)impactMedium { [self impactWithStyle:UIImpactFeedbackStyleMedium]; }
+ (void)impactHeavy  { [self impactWithStyle:UIImpactFeedbackStyleHeavy]; }

+ (void)impactSoft {
    if (@available(iOS 13.0, *)) {
        [self impactWithStyle:UIImpactFeedbackStyleSoft];
    }
}

+ (void)impactRigid {
    if (@available(iOS 13.0, *)) {
        [self impactWithStyle:UIImpactFeedbackStyleRigid];
    }
}

+ (void)selectionChanged {
    if (![self isEnabled] || ![self canTriggerFeedback]) return;
    if (@available(iOS 10.0, *)) {
        UISelectionFeedbackGenerator *generator = [[UISelectionFeedbackGenerator alloc] init];
        [generator selectionChanged];
    }
}

+ (void)notifyWithType:(UINotificationFeedbackType)type {
    if (![self isEnabled] || ![self canTriggerFeedback]) return;
    if (@available(iOS 10.0, *)) {
        UINotificationFeedbackGenerator *generator = [[UINotificationFeedbackGenerator alloc] init];
        [generator notificationOccurred:type];
    }
}

+ (void)notifySuccess { [self notifyWithType:UINotificationFeedbackTypeSuccess]; }
+ (void)notifyWarning { [self notifyWithType:UINotificationFeedbackTypeWarning]; }
+ (void)notifyError   { [self notifyWithType:UINotificationFeedbackTypeError]; }

@end
